from rest_framework import serializers
from .models import Interface, Case, CaseExecutionRecord


class InterfaceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Interface
        fields = ['id', 'name', 'project', 'method', 'url', 'params', 'data', 'json', 'cookies', 'headers']

class CaseExecutionRecordSerializer(serializers.ModelSerializer):
    class Meta:
        model = CaseExecutionRecord
        fields = ['id', 'case', 'status', 'result', 'report_url', 'created_at', 'updated_at']

class CaseSerializer(serializers.ModelSerializer):
    interface_info = InterfaceSerializer(source='interface', read_only=True)
    project_name = serializers.CharField(source='project.name', read_only=True)
    latest_execution = serializers.SerializerMethodField()
    
    class Meta:
        model = Case
        fields = ['id', 'name', 'title', 'description', 'url', 'method', 'headers', 'params', 'body', 
                 'expected_result', 'priority', 'project', 'project_name', 'interface', 'interface_info',
                 'allure', 'api_args', 'extract', 'validate', 'created_time', 'updated_time', 'latest_execution']
        read_only_fields = ['interface_info', 'project_name', 'created_time', 'updated_time', 'latest_execution']
        extra_kwargs = {
            'interface': {'required': False},
            'name': {'required': False}
        }

    def get_latest_execution(self, obj):
        record = obj.executions.first()
        if record:
            return CaseExecutionRecordSerializer(record).data
        return None

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        return ret